package com.rpp.service.impl;

import com.rpp.dao.OrderRepository;
import com.rpp.domain.Order;
import com.rpp.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * @Description
 * @Author peng
 * @Date 2020/10/28 10:55 上午
 */
@Service
public class OrderService implements IOrderService {

    @Autowired
    OrderRepository orderRepository;

    @Override
    public List<Order> findAll() {
        return orderRepository.findAll(Sort.by(Sort.Direction.ASC, "id"));
    }

    /**
     * 创建订单
     *
     * @return
     */
    @Override
    public Order createOrder() {
        Order order = new Order();
        order.setName("测试");
        order.setAmount(new BigDecimal(new Random().nextInt(100)));
        order.setStatus("待支付");
        order.setCreateDate(new Date());
        return orderRepository.save(order);
    }

    /**
     * 支付订单
     *
     * @param id
     */
    @Override
    public Map payOrder(Long id) {
        Order order = orderRepository.findById(id).get();
        Map result = new HashMap();
        if (null == order) {
            result.put("msg", "订单不存在");
            return result;
        }
        if (!order.getStatus().equals("待支付")) {
            result.put("msg", "订单已结束，不能支付");
            return result;
        }
        orderRepository.updateOrderStatus(id, "已支付");
        result.put("msg", "支付成功");
        return result;
    }

    /**
     * 关闭订单
     *
     * @param orderId
     * @return
     */
    @Override
    public Boolean closeOrder(Long orderId) {
        Order order = orderRepository.findById(orderId).get();
        if (null == order) {
            return true;
        }
        if (order.getStatus().equals("已支付")) {
            return true;
        }
        int res = orderRepository.updateOrderStatus(orderId, "已关闭");
        return res > 0;
    }
}
